package com.soujiayi.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.soujiayi.model.UpdateInfo;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.share.WeixinAPI;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.soujiayi.util.FileCache;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;

public class SettingActivity extends Activity {
	private UpdateManager updateMan;
	private ProgressDialog updateProgressDialog;
	private ProgressDialog mProgressDialog;
	private FileCache fileCache;
	private Handler handler;
	private int CHECK_UPDATE = 1, CLEAR_CACHE = 2;
	private String fileSize = "0M";
	private DatabaseManager databaseManager = new DatabaseManager(
			SettingActivity.this);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.settings);
		mProgressDialog = new ProgressDialog(this);
		updateMan = new UpdateManager(this, appUpdateCb);
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == CLEAR_CACHE) {
					mProgressDialog.dismiss();
					Toast.makeText(
							SettingActivity.this,
							SettingActivity.this
									.getResources()
									.getString(
											R.string.settings_clear_cache_success)
									.replace("?", fileSize), Toast.LENGTH_SHORT)
							.show();
				}

			};
		};
	}

	public void back(View view) {
		Intent intent = new Intent(SettingActivity.this, IndexActivity.class);
		startActivity(intent);
		this.finish();
		overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
	}

	public void userCenter(View view) {
		User user = databaseManager.getOnlineUser();
		if (!NetworkUtils.isNetworkConnected(this)) {
			databaseManager.deleteAllFavorites("goods");
			databaseManager.deleteAllFavorites("mall");
			UserKeeper.clear(SettingActivity.this);
			Intent intent = new Intent(SettingActivity.this,
					SoujiayiLoginActivity.class);
			startActivity(intent);
		} else {
			if (user == null || CommonUtils.isEmpty(user.getUsername())||user.getStatus()==0) {
				Intent intent = new Intent(SettingActivity.this,
						SoujiayiLoginActivity.class);
				startActivity(intent);
			} else {
				Intent intent = new Intent(SettingActivity.this,
						UserCenterActivity.class);
				startActivity(intent);
			}
		}
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void checkUpdate(View view) {
		if (NetworkUtils.isNetworkConnected(this)) {
			mProgressDialog.setTitle(this
					.getString(R.string.settings_check_update));
			mProgressDialog.setMessage(this
					.getString(R.string.settings_checking_update));
			mProgressDialog.show();
			updateMan.checkUpdate();
		} else {
			Toast.makeText(
					SettingActivity.this,
					SettingActivity.this.getResources().getString(
							R.string.network_disconnect), Toast.LENGTH_SHORT)
					.show();
		}
	}

	public void aboutUs(View view) {
		Intent intent = new Intent(SettingActivity.this, AboutUsActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void statement(View view) {
		Intent intent = new Intent(SettingActivity.this,
				StatementActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void contactUs(View view) {
		Intent intent = new Intent(SettingActivity.this,
				ContactUsActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void clearCache(View view) {
		// if (clearCacheSuccess != null || clearCacheSuccess.equals("")) {
		// clearCacheSuccess = SettingActivity.this.getResources().getString(
		// R.string.settings_clear_cache_success);
		// }
		if (fileCache == null) {
			fileCache = new FileCache(SettingActivity.this);
		}

		mProgressDialog = new ProgressDialog(SettingActivity.this);
		mProgressDialog.setMessage(getResources().getString(
				R.string.settings_clearing_cache));
		mProgressDialog.setCancelable(false);
		Window window = mProgressDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.alpha = 0.7f;// 透明度
		lp.dimAmount = 0.5f;// 黑暗度
		window.setAttributes(lp);
		mProgressDialog.show();
		new Thread(new Runnable() {
			@Override
			public void run() {
				fileSize = fileCache.clear();
				handler.sendEmptyMessageDelayed(CLEAR_CACHE, 2000);
			}
		}).start();
	}

	public void skimHistory(View view) {
		Intent intent = new Intent(SettingActivity.this,
				SkimHistoryActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void shareSetting(View view) {
		Intent intent = new Intent(SettingActivity.this,
				ShareSettingActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void shareToWeixin(View view) {
		if (CommonUtils.isAppInstalled(this, "com.tencent.mm")) {
			WeixinAPI api = new WeixinAPI(this);
			api.shareToWeixin();
		} else {
			AlertDialog.Builder builder = new Builder(SettingActivity.this);
			builder.setTitle(SettingActivity.this
					.getString(R.string.weixin_download_title));
			builder.setMessage(SettingActivity.this
					.getString(R.string.weixin_download_message));

			builder.setPositiveButton(
					SettingActivity.this.getString(R.string.confirm),
					new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							Uri uri = Uri.parse("http://weixin.qq.com/m");
							Intent it = new Intent(Intent.ACTION_VIEW, uri);
							startActivity(it);
						}
					});

			builder.setNegativeButton(
					SettingActivity.this.getString(R.string.cancel),
					new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			Dialog noticeDialog = builder.create();
			noticeDialog.show();
		}
	}

	public void adviceAndFeedback(View view) {
		Intent intent = new Intent(SettingActivity.this,
				AdviceAndFeedbackActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void shareWithFriends(View view) {
		final CharSequence[] items = {
				getResources().getString(R.string.share_send_sms),
				getResources().getString(R.string.share_send_email),
				getResources().getString(R.string.share_send_to_weibo) };
		final String shareContent = getResources().getString(
				R.string.share_content);
		final String shareMailSubject = getResources().getString(
				R.string.share_send_email_subject);
		AlertDialog.Builder builder = new AlertDialog.Builder(
				SettingActivity.this);
		builder.setTitle(
				getResources().getString(R.string.settings_share_with_friends))
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
						case 0:
							Uri uri = Uri.parse("smsto:");
							Intent smsIt = new Intent(Intent.ACTION_SENDTO, uri);
							smsIt.putExtra("sms_body", shareContent);
							SettingActivity.this.startActivity(smsIt);
							break;
						case 1:
							Uri mallto = Uri.parse("mailto:");

							Intent mailIt = new Intent(Intent.ACTION_SENDTO,
									mallto);
							mailIt.putExtra(Intent.EXTRA_SUBJECT,
									shareMailSubject);
							mailIt.putExtra(Intent.EXTRA_TEXT, shareContent);
							try {
								SettingActivity.this.startActivity(mailIt);
							} catch (Exception e) {
								Toast.makeText(
										SettingActivity.this,
										SettingActivity.this
												.getString(R.string.share_to_mailbox_failed),
										Toast.LENGTH_LONG).show();
							}
							break;
						case 2:
							Intent intent = new Intent(SettingActivity.this,
									ShareActivity.class);
							startActivity(intent);
							overridePendingTransition(R.anim.push_left_in,
									R.anim.push_left_out);
							break;
						default:
							break;
						}
					}
				});
		Dialog dialog = builder.create();

		dialog.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onBackPressed() {
		if (updateProgressDialog != null && updateProgressDialog.isShowing()) {
			updateMan.cancelDownload();
			updateProgressDialog.dismiss();
		} else {
			super.onBackPressed();
			Intent intent = new Intent(SettingActivity.this,
					IndexActivity.class);
			startActivity(intent);
			SettingActivity.this.finish();
			overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
		}
	}

	// 自动更新回调函数
	UpdateManager.UpdateCallback appUpdateCb = new UpdateManager.UpdateCallback() {

		public void downloadProgressChanged(int progress) {
			if (updateProgressDialog != null
					&& updateProgressDialog.isShowing()) {
				updateProgressDialog.setProgress(progress);
			}

		}

		public void downloadCompleted(Boolean success, CharSequence errorMsg) {
			if (updateProgressDialog != null
					&& updateProgressDialog.isShowing()) {
				updateProgressDialog.dismiss();
			}
			if (success) {
				updateMan.update();
			} else {
				AlertDialog.Builder builder = new Builder(SettingActivity.this);
				builder.setTitle(R.string.soft_reupdate_title);
				builder.setMessage(R.string.soft_update_failed_info);
				// 更新
				builder.setPositiveButton(R.string.soft_reupdate,
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								// 显示下载对话框
								updateProgressDialog = new ProgressDialog(
										SettingActivity.this);
								updateProgressDialog
										.setMessage(getText(R.string.dialog_downloading_msg));
								updateProgressDialog.setIndeterminate(false);
								updateProgressDialog
										.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
								updateProgressDialog.setMax(100);
								updateProgressDialog.setProgress(0);
								updateProgressDialog.show();

								updateMan.downloadPackage();

							}
						});
				// 稍后更新
				builder.setNegativeButton(R.string.soft_update_later,
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				Dialog noticeDialog = builder.create();
				noticeDialog.show();
			}
		}

		public void downloadCanceled() {
			if (updateProgressDialog != null
					&& updateProgressDialog.isShowing())
				updateProgressDialog.dismiss();
		}

		public void checkUpdateCompleted(Boolean hasUpdate,
				UpdateInfo updateInfo) {
			mProgressDialog.dismiss();
			if (hasUpdate) {
				// 构造对话框
				AlertDialog.Builder builder = new Builder(SettingActivity.this);
				builder.setTitle(R.string.soft_update_title);
				builder.setMessage(SettingActivity.this
						.getString(R.string.newVersion)
						+ updateInfo.getVerName()
						+ "\n"
						+ SettingActivity.this.getString(R.string.appSize)
						+ updateInfo.getSize()
						+ "\n"
						+ SettingActivity.this.getString(R.string.updateLog)
						+ "\n" + updateInfo.getDesc());
				// 更新
				builder.setPositiveButton(R.string.soft_update_now,
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								// 显示下载对话框
								updateProgressDialog = new ProgressDialog(
										SettingActivity.this);
								updateProgressDialog
										.setMessage(getText(R.string.dialog_downloading_msg));
								updateProgressDialog.setIndeterminate(false);
								updateProgressDialog
										.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
								updateProgressDialog.setMax(100);
								updateProgressDialog.setProgress(0);
								updateProgressDialog.show();

								updateMan.downloadPackage();
							}
						});
				// 稍后更新
				builder.setNegativeButton(R.string.soft_update_later,
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				Dialog noticeDialog = builder.create();
				noticeDialog.show();
			} else {
				Toast.makeText(
						SettingActivity.this,
						SettingActivity.this.getString(R.string.soft_update_no),
						Toast.LENGTH_SHORT).show();
			}

		}
	};
}
